document.addEventListener('DOMContentLoaded', function() {
    // 加载配置列表
    loadConfigs();
    
    // 添加配置按钮点击事件
    document.getElementById('addConfigBtn').addEventListener('click', function() {
        // 重置表单
        document.getElementById('configForm').reset();
        document.getElementById('configId').value = '';
        document.getElementById('configModalLabel').textContent = '添加配置';
        
        // 显示模态框
        const configModal = new bootstrap.Modal(document.getElementById('configModal'));
        configModal.show();
    });
    
    // 保存配置按钮点击事件
    document.getElementById('saveConfigBtn').addEventListener('click', function() {
        saveConfig();
    });
    
    // 消息类型切换事件
    document.getElementById('messageType').addEventListener('change', function() {
        updateMessageForm();
    });
    
    // 发送消息按钮点击事件
    document.getElementById('sendMessageBtn').addEventListener('click', function() {
        sendMessage();
    });
    
    // 消息内容变化事件
    document.getElementById('messageContent').addEventListener('input', updateMessagePreview);
    document.getElementById('messageTitle').addEventListener('input', updateMessagePreview);
    document.getElementById('messageDescription').addEventListener('input', updateMessagePreview);
    
    // 发送记录相关事件
    document.getElementById('applyFilterBtn').addEventListener('click', function() {
        loadHistory();
    });
    
    document.getElementById('refreshHistoryBtn').addEventListener('click', function() {
        loadHistory();
    });
    
    // 初始化发送记录
    loadHistory();
});

// 加载配置列表
function loadConfigs() {
    fetch('/api/config')
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                const configs = result.data;
                renderConfigTable(configs);
                updateDestinationSelect(configs);
            } else {
                showAlert('加载配置失败：' + result.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('加载配置失败：' + error, 'danger');
        });
}

// 渲染配置表格
function renderConfigTable(configs) {
    const tableBody = document.getElementById('configTableBody');
    tableBody.innerHTML = '';
    
    if (configs.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="6" class="text-center">暂无配置</td>';
        tableBody.appendChild(row);
        return;
    }
    
    configs.forEach(config => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${config.id}</td>
            <td>${config.name}</td>
            <td>${config.corpId}</td>
            <td>${config.agentId}</td>
            <td>${config.enabled ? '<span class="badge bg-success">启用</span>' : '<span class="badge bg-secondary">禁用</span>'}</td>
            <td>
                <button class="btn btn-sm btn-primary edit-btn" data-id="${config.id}">编辑</button>
                <button class="btn btn-sm btn-danger delete-btn" data-id="${config.id}">删除</button>
                <button class="btn btn-sm btn-info test-btn" data-id="${config.id}">测试</button>
            </td>
        `;
        tableBody.appendChild(row);
        
        // 添加编辑按钮点击事件
        row.querySelector('.edit-btn').addEventListener('click', function() {
            editConfig(config.id);
        });
        
        // 添加删除按钮点击事件
        row.querySelector('.delete-btn').addEventListener('click', function() {
            deleteConfig(config.id);
        });
        
        // 添加测试按钮点击事件
        row.querySelector('.test-btn').addEventListener('click', function() {
            testConfig(config.id);
        });
    });
}

// 更新目的地选择框
function updateDestinationSelect(configs) {
    const messageSelect = document.getElementById('messageDestination');
    const filterSelect = document.getElementById('filterDestination');
    
    // 更新消息发送目的地选择框
    updateSelect(messageSelect, configs, '暂无可用配置');
    
    // 更新筛选目的地选择框
    updateSelect(filterSelect, configs, '全部');
}

// 更新选择框通用函数
function updateSelect(select, configs, emptyText) {
    select.innerHTML = '';
    
    // 添加"全部"选项（仅用于筛选）
    if (select.id === 'filterDestination') {
        const allOption = document.createElement('option');
        allOption.value = 'all';
        allOption.textContent = '全部';
        select.appendChild(allOption);
    }
    
    if (configs.length === 0) {
        const option = document.createElement('option');
        option.value = '';
        option.textContent = emptyText;
        option.disabled = true;
        select.appendChild(option);
        return;
    }
    
    configs.forEach(config => {
        if (config.enabled) {
            const option = document.createElement('option');
            option.value = config.id;
            option.textContent = `${config.name} (ID: ${config.id})`;
            select.appendChild(option);
        }
    });
}

// 编辑配置
function editConfig(id) {
    fetch(`/api/config/${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                const config = result.data;
                
                // 填充表单
                document.getElementById('configId').value = config.id;
                document.getElementById('configName').value = config.name;
                document.getElementById('configCorpId').value = config.corpId;
                document.getElementById('configAgentId').value = config.agentId;
                document.getElementById('configSecret').value = config.secret;
                document.getElementById('configEnabled').checked = config.enabled;
                document.getElementById('configRemark').value = config.remark || '';
                
                // 更新模态框标题
                document.getElementById('configModalLabel').textContent = '编辑配置';
                
                // 显示模态框
                const configModal = new bootstrap.Modal(document.getElementById('configModal'));
                configModal.show();
            } else {
                showAlert('加载配置失败：' + result.message, 'danger');
            }
        })
        .catch(error => {
            showAlert('加载配置失败：' + error, 'danger');
        });
}

// 保存配置
function saveConfig() {
    const id = document.getElementById('configId').value;
    const config = {
        name: document.getElementById('configName').value,
        corpId: document.getElementById('configCorpId').value,
        agentId: parseInt(document.getElementById('configAgentId').value),
        secret: document.getElementById('configSecret').value,
        enabled: document.getElementById('configEnabled').checked,
        remark: document.getElementById('configRemark').value
    };
    
    const url = id ? `/api/config/${id}` : '/api/config';
    const method = id ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
    })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                // 关闭模态框
                const configModal = bootstrap.Modal.getInstance(document.getElementById('configModal'));
                configModal.hide();
                
                // 重新加载配置列表
                loadConfigs();
                
                showAlert(id ? '配置更新成功' : '配置添加成功', 'success');
            } else {
                showAlert((id ? '更新' : '添加') + '配置失败：' + result.message, 'danger');
            }
        })
        .catch(error => {
            showAlert((id ? '更新' : '添加') + '配置失败：' + error, 'danger');
        });
}

// 删除配置
function deleteConfig(id) {
    if (confirm('确定要删除此配置吗？')) {
        fetch(`/api/config/${id}`, {
            method: 'DELETE'
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    // 重新加载配置列表
                    loadConfigs();
                    
                    showAlert('配置删除成功', 'success');
                } else {
                    showAlert('删除配置失败：' + result.message, 'danger');
                }
            })
            .catch(error => {
                showAlert('删除配置失败：' + error, 'danger');
            });
    }
}

// 测试配置
function testConfig(id) {
    fetch(`/api/config/test/${id}`)
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                showAlert('测试消息发送成功', 'success');
            } else {
                showAlert('测试消息发送失败：' + result.data, 'danger');
            }
        })
        .catch(error => {
            showAlert('测试消息发送失败：' + error, 'danger');
        });
}

// 更新消息表单
function updateMessageForm() {
    const messageType = document.getElementById('messageType').value;
    
    // 隐藏所有可选字段
    document.getElementById('contentGroup').classList.add('d-none');
    document.getElementById('titleGroup').classList.add('d-none');
    document.getElementById('descriptionGroup').classList.add('d-none');
    document.getElementById('urlGroup').classList.add('d-none');
    document.getElementById('picUrlGroup').classList.add('d-none');
    
    // 根据消息类型显示相应字段
    switch (messageType) {
        case 'text':
        case 'markdown':
            document.getElementById('contentGroup').classList.remove('d-none');
            break;
        case 'news':
            document.getElementById('titleGroup').classList.remove('d-none');
            document.getElementById('descriptionGroup').classList.remove('d-none');
            document.getElementById('urlGroup').classList.remove('d-none');
            document.getElementById('picUrlGroup').classList.remove('d-none');
            break;
        case 'template_card':
            document.getElementById('titleGroup').classList.remove('d-none');
            document.getElementById('descriptionGroup').classList.remove('d-none');
            document.getElementById('urlGroup').classList.remove('d-none');
            break;
    }
    
    // 更新消息预览
    updateMessagePreview();
}

// 更新消息预览
function updateMessagePreview() {
    const messageType = document.getElementById('messageType').value;
    const preview = document.getElementById('messagePreview');
    
    switch (messageType) {
        case 'text':
            const textContent = document.getElementById('messageContent').value || '消息内容';
            preview.innerHTML = `<div class="text-message">${textContent}</div>`;
            break;
        case 'markdown':
            const markdownContent = document.getElementById('messageContent').value || '# 标题\n**加粗文本**\n> 引用文本';
            // 简单的Markdown渲染
            const rendered = markdownContent
                .replace(/^# (.*?)$/gm, '<h1>$1</h1>')
                .replace(/^## (.*?)$/gm, '<h2>$1</h2>')
                .replace(/^### (.*?)$/gm, '<h3>$1</h3>')
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
                .replace(/\*(.*?)\*/g, '<em>$1</em>')
                .replace(/^> (.*?)$/gm, '<blockquote>$1</blockquote>')
                .replace(/\n/g, '<br>');
            preview.innerHTML = `<div class="markdown-message">${rendered}</div>`;
            break;
        case 'news':
            const newsTitle = document.getElementById('messageTitle').value || '消息标题';
            const newsDescription = document.getElementById('messageDescription').value || '消息描述';
            const newsUrl = document.getElementById('messageUrl').value || '#';
            const newsPicUrl = document.getElementById('messagePicUrl').value || 'https://via.placeholder.com/300x200';
            preview.innerHTML = `
                <div class="card news-message">
                    <img src="${newsPicUrl}" class="card-img-top" alt="图片">
                    <div class="card-body">
                        <h5 class="card-title">${newsTitle}</h5>
                        <p class="card-text">${newsDescription}</p>
                        <a href="${newsUrl}" class="btn btn-primary btn-sm">查看详情</a>
                    </div>
                </div>
            `;
            break;
        case 'template_card':
            const cardTitle = document.getElementById('messageTitle').value || '消息标题';
            const cardDescription = document.getElementById('messageDescription').value || '消息描述';
            const cardUrl = document.getElementById('messageUrl').value || '#';
            preview.innerHTML = `
                <div class="card template-card">
                    <div class="card-header">
                        企业微信通知
                    </div>
                    <div class="card-body">
                        <h5 class="card-title">${cardTitle}</h5>
                        <p class="card-text">${cardDescription}</p>
                        <a href="${cardUrl}" class="btn btn-primary btn-sm">查看详情</a>
                    </div>
                    <div class="card-footer text-muted">
                        来自企业微信应用
                    </div>
                </div>
            `;
            break;
    }
}

// 发送消息
function sendMessage() {
    const destinationId = document.getElementById('messageDestination').value;
    const messageType = document.getElementById('messageType').value;
    
    if (!destinationId) {
        showAlert('请选择目的地', 'warning');
        return;
    }
    
    let url = `/api/message/${messageType}?destinationId=${destinationId}`;
    let method = 'POST';
    let headers = {};
    let body;
    
    switch (messageType) {
        case 'text':
        case 'markdown':
            headers['Content-Type'] = 'text/plain';
            body = document.getElementById('messageContent').value;
            break;
        case 'news':
            headers['Content-Type'] = 'application/json';
            body = JSON.stringify({
                title: document.getElementById('messageTitle').value,
                description: document.getElementById('messageDescription').value,
                url: document.getElementById('messageUrl').value,
                picUrl: document.getElementById('messagePicUrl').value
            });
            break;
        case 'template_card':
            headers['Content-Type'] = 'application/json';
            body = JSON.stringify({
                title: document.getElementById('messageTitle').value,
                description: document.getElementById('messageDescription').value,
                url: document.getElementById('messageUrl').value
            });
            break;
    }
    
    fetch(url, {
        method: method,
        headers: headers,
        body: body
    })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                showAlert('消息发送成功', 'success');
            } else {
                showAlert('消息发送失败：' + result.data, 'danger');
            }
        })
        .catch(error => {
            showAlert('消息发送失败：' + error, 'danger');
        });
}

// 加载发送记录
function loadHistory() {
    const statusFilter = document.getElementById('filterStatus').value;
    const destinationFilter = document.getElementById('filterDestination').value;
    
    let url = '/api/message/history';
    const params = new URLSearchParams();
    
    if (statusFilter !== 'all') {
        params.append('status', statusFilter);
    }
    if (destinationFilter !== 'all') {
        params.append('destinationId', destinationFilter);
    }
    
    if (params.toString()) {
        url += '?' + params.toString();
    }
    
    // 同时加载配置信息以获取目的地名称
    Promise.all([
        fetch(url).then(response => response.json()),
        fetch('/api/config').then(response => response.json())
    ])
    .then(([historyResult, configResult]) => {
        if (historyResult.code === 200 && configResult.code === 200) {
            const historyData = historyResult.data;
            const configs = configResult.data;
            
            // 为每条记录添加目的地名称
            const enrichedData = historyData.map(record => {
                const config = configs.find(c => c.id === record.destinationId);
                return {
                    ...record,
                    destinationName: config ? config.name : '未知配置'
                };
            });
            
            renderHistoryTable(enrichedData);
            updateHistoryPagination(enrichedData.length);
        } else {
            showAlert('加载发送记录失败', 'danger');
        }
    })
    .catch(error => {
        showAlert('加载发送记录失败：' + error, 'danger');
    });
}

// 渲染发送记录表格
function renderHistoryTable(records) {
    const tableBody = document.getElementById('historyTableBody');
    tableBody.innerHTML = '';
    
    if (records.length === 0) {
        const row = document.createElement('tr');
        row.innerHTML = '<td colspan="6" class="text-center">暂无发送记录</td>';
        tableBody.appendChild(row);
        return;
    }
    
    records.forEach(record => {
        const row = document.createElement('tr');
        const contentPreview = record.content ? record.content.substring(0, 50) + (record.content.length > 50 ? '...' : '') : '';
        
        row.innerHTML = `
            <td>${moment(record.createTime).format('YYYY-MM-DD HH:mm:ss')}</td>
            <td>${record.destinationName || '未知'}</td>
            <td>${getMessageTypeText(record.messageType)}</td>
            <td title="${record.content || ''}">${contentPreview}</td>
            <td title="${record.errorMessage}">${getStatusBadge(record.status)}</td>
            <td>
                <button class="btn btn-sm btn-primary resend-btn" data-id="${record.id}">重新发送</button>
            </td>
        `;
        tableBody.appendChild(row);
        
        // 添加重新发送按钮点击事件
        row.querySelector('.resend-btn').addEventListener('click', function() {
            resendMessage(record.id);
        });
    });
}

// 获取消息类型文本
function getMessageTypeText(type) {
    const types = {
        'text': '文本',
        'markdown': 'Markdown',
        'news': '图文',
        'template_card': '模板卡片'
    };
    return types[type] || type;
}

// 获取状态徽章
function getStatusBadge(status) {
    const badges = {
        'SUCCESS': '<span class="badge bg-success">成功</span>',
        'FAILED': '<span class="badge bg-danger">失败</span>',
        'PENDING': '<span class="badge bg-warning">处理中</span>'
    };
    return badges[status] || `<span class="badge bg-secondary">${status}</span>`;
}

// 更新历史记录分页信息
function updateHistoryPagination(totalRecords) {
    const infoElement = document.getElementById('historyPaginationInfo');
    infoElement.textContent = `显示 ${totalRecords} 条记录`;
}

// 重新发送消息
function resendMessage(historyId) {
    if (confirm('确定要重新发送这条消息吗？')) {
        fetch(`/api/message/resend/${historyId}`, {
            method: 'POST'
        })
            .then(response => response.json())
            .then(result => {
                if (result.code === 200) {
                    showAlert('消息已重新发送', 'success');
                    // 重新加载发送记录
                    loadHistory();
                } else {
                    showAlert('重新发送失败：' + result.message, 'danger');
                }
            })
            .catch(error => {
                showAlert('重新发送失败：' + error, 'danger');
            });
    }
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.setAttribute('role', 'alert');
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    `;
    
    // 添加到页面顶部
    const container = document.querySelector('.container');
    container.insertBefore(alertDiv, container.firstChild);
    
    // 5秒后自动关闭
    setTimeout(() => {
        const bsAlert = new bootstrap.Alert(alertDiv);
        bsAlert.close();
    }, 5000);
}